package com.example.common.security.service;

import cn.hutool.core.util.StrUtil;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.constants.Constants;
import com.example.common.core.constants.HttpConstants;
import com.example.common.core.constants.JwtConstants;
import com.example.common.core.domain.RedisUser;
import com.example.common.core.utils.JwtUtils;
import com.example.common.core.utils.ThreadLocalUtil;
import com.example.common.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TokenService {
    @Autowired
    private RedisService redisService;


    public String createToken(Long userId,String secret,Integer identity,String nick,String headImage) {
        // 生成token
        Map<String,Object> claims = new HashMap<>();
//        String userkey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID, userId);
//        claims.put(JwtConstants.LOGIN_USER_KEY, userkey);
        claims.put(JwtConstants.LOGIN_USER_NICK, nick);

        String token = JwtUtils.createToken(claims, secret);

        //拼接redis key
        String key = getTokenKey(userId);
        RedisUser redisUser = new RedisUser();

        redisUser.setUserNick(nick);
//        loginUser.setUserkey(userkey);
        redisUser.setIdentity(identity);
        redisUser.setHeadImage(headImage);

        // 保存token到redis
        redisService.setCacheObject(key, redisUser,CacheConstants.EXPIRATION, TimeUnit.MINUTES);



        return token;

    }

    public String getTokenKey(Long userkey) {
        return CacheConstants.LOGIN_TOKEN_KEY + userkey;
    }

    public void extendToken(String token,String secret) {

        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        String tokenKey = getTokenKey(userId);

        Long time = redisService.getExpire(tokenKey,TimeUnit.MINUTES);
        if (time != null && time <= CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey,CacheConstants.EXPIRATION,TimeUnit.MINUTES);
        }

    }

    public Long getUserId(String token, String secret) {
        Claims claims = null;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息 解析payload中信息
            if (claims == null) {
                log.error("解析token异常:{}",token);
            }
        } catch (Exception e) {
            log.error("解析token异常:{},出现异常",token,e);
        }
        return JwtUtils.getUserId(claims);
    }

    public RedisUser getRedisUser(String token, String secret) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class); //失败返回-1
        if (userId == -1L) {
            return null;
        }
        String redisKey = getTokenKey(userId);
        RedisUser redisUser = redisService.getCacheObject(redisKey, RedisUser.class);
        return redisUser;
    }

    public boolean exitLogin(String token,String secret) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        if (userId == null) {
            return false;
        }
        String redisKey = getTokenKey(userId);
        return redisService.deleteObject(redisKey);
    }
    public void refreshLoginUser(String nickName, String headImage, Long userKey) {
        String tokenKey = getTokenKey(userKey);
        RedisUser loginUser = redisService.getCacheObject(tokenKey, RedisUser.class);
        loginUser.setUserNick(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }
}
